import {
  request
} from "../../request/index.js"

import regeneratorRuntime from '../../lib/runtime/runtime'
Page({

  data: {
    goodsObj: {},
    isCollect:false
  },
  GoodsInfo: {},

  onShow: function () {
    let pages =  getCurrentPages();
    let currentPage = pages[pages.length-1]
    let options = currentPage.options
    
    const {
      goods_id
    } = options
    this.getGoodsDetail(goods_id)


  },
  async getGoodsDetail(goods_id) {
    const goodsObj = await request({
      url: "/goods/detail",
      data: {
        goods_id
      }
    })
    this.GoodsInfo = goodsObj

    let collect = wx.getStorageSync("collect")||[];
    let isCollect = collect.some(v=>v.goods_id===this.GoodsInfo.goods_id)


    this.setData({
      goodsObj: {
        goods_name: goodsObj.goods_name,
        goods_price: goodsObj.goods_price,
        goods_introduce: goodsObj.goods_introduce.replace(/\.webp/g, '.jpg'),
        pics: goodsObj.pics,
      },
      isCollect
    })
  },

  handlePrevewImage(e) {
    const urls = this.GoodsInfo.pics.map(v => v.pics_mid)
    const currentUrl = e.currentTarget.dataset.url
    wx.previewImage({
      current: currentUrl, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },
  //加入购物车
  handleCartAdd() {
    //获取缓存中数据
    let cart = wx.getStorageSync('cart') || [];
    //判断商品对象是否存在数组
    let index = cart.findIndex(v => v.goods_id === this.GoodsInfo.goods_id)
    if (index === -1) {
      //不存在  第一次添加
      this.GoodsInfo.num = 1
      this.GoodsInfo.checked = true
      cart.push(this.GoodsInfo)
    } else {
      //存在 继续添加  执行num++
      cart[index].num++
    }
    //把购物车重新添加回缓存中
    wx.setStorageSync('cart', cart);
    //弹窗提示
    wx.showToast({
      title: '加入成功',
      icon: 'success',
      mask: true,
    });
  },

  handleCollect(){
    let isCollect = false
    let collect = wx.getStorageSync("collect")||[];
    let index = collect.findIndex(v=>v.goods_id===this.GoodsInfo.goods_id)
    if(index!==-1){
      collect.splice(index,1)
      isCollect = false
      wx.showToast({
        title: '取消收藏',
        icon: 'success',
        mask: true,
      });
    }else{
      collect.push(this.GoodsInfo)
      isCollect = true
      wx.showToast({
        title: '收藏成功',
        icon: 'success',
        mask: true,
      });
    }
    wx.setStorageSync("collect", collect);

    this.setData({
      isCollect
    })

  }

})